/**
 * 子进程，处理文件转换等耗时的工作，不会阻塞主进程，导致卡死
 */

// const AsposePdf = require('./Aspose.PDF-for-Node.js-via-CPP-23.11/AsposePDFforNode.cjs')
// import PDFParser from 'pdf-parser'
import PDFParser from 'pdf2json'
import fs from 'fs'
import path from 'path'
// import { PDFDocument } from 'pdf-lib'

process.parentPort.on('message', async (e) => {
  const port = e.ports[0]

  port.start()
  port.postMessage({ data: 'Ready' })

  const { files, outputManage } = e.data
  const { outputPath, equalSource } = outputManage

  return new Promise((resolve: any): any => {
    async function pdfToImage(savePath, fileItem) {
      const { filePath, fileId } = fileItem

      const out_dir = equalSource ? path.dirname(filePath) : savePath
      try {
        return await new Promise(async (p) => {
          

          const file = fs.readFileSync(filePath)
          // const pdfDoc = await PDFDocument.load(file)
          // const pages = pdfDoc.getPages()

          // pdfParser.pdf2json(filePath, function (error, pdf) {
          //   if (error != null) {
          //     console.log('报错：', error)
          //   } else {
          //     console.log('pdf内容', pdf)
          //     p({
          //       fileId,
          //       success: true,
          //       content: pdf
          //     })
          //   }
          // })
          p({
            fileId: ''
          })
        })
      } catch (error) {
        console.log(error)
      }
      return
    }

    // 等待所有异步操作完成再统一返回
    Promise.all(
      files.map((item) => {
        return new Promise(async (resolve) => {
          const result = await pdfToImage(outputPath, item).catch((err) =>
            console.log('***err', err)
          )
          resolve(result)
        })
      })
    ).then((res) => {
      process.parentPort.postMessage({ data: res, processCode: 'done' })
      resolve(res) as any
    })
  })
})
